package com.stylefeng.guns.rest.modular.file;

import java.io.IOException;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestMapping;

import com.stylefeng.guns.core.util.FileUtil;
import com.stylefeng.guns.rest.config.properties.GunsProperties;

@Controller
@RequestMapping("/app")
public class FileController {
	
	private static Logger log = LoggerFactory.getLogger(FileController.class);
	
    @Resource
    private GunsProperties gunsProperties;
    
    
    /**
     * 返回图片
     *
     * @author stylefeng
     * @Date 2017/5/24 23:00
     */
    @RequestMapping("/{pictureId}")
    public void renderPicture(@PathVariable("pictureId") String pictureId, HttpServletResponse response) {
        String path = gunsProperties.getFileUploadPath() + pictureId + ".jpg";
        try {
            byte[] bytes = FileUtil.toByteArray(path);
            response.getOutputStream().write(bytes);
        }catch (Exception e){
             e.printStackTrace();
             log.info("图片下载失败:"+path);
        }
    }
    
    
    //我的,暂保留吧
    // http://127.0.0.1:8081/app/downloadFile?filePath=
    // http://127.0.0.1:8081/app/downloadFile?filePath=D:/home/test.jpg
    @RequestMapping(value = "/downloadFile")
    public void downloadImg(HttpServletRequest request,HttpServletResponse response, String filePath) {
    	String fileSavePath = gunsProperties.getFileUploadPath();
		if(filePath.startsWith(fileSavePath)){
			FileUtil.downloadFile(filePath,response);
		}else{
			log.warn("非法下载目录:"+filePath);
		}
    }
	
	
	
	
	
	
	
	
	
	
	//
}
